import { Component, EventTouch, NodeEventType, Vec2, _decorator, v2,Event, CCBoolean, Node } from "cc";
const { ccclass, property } = _decorator;
/**
 * 封装一个Click事件，通过计算start和end两点之间的差距和时间差，判断是否触发Click事件
 */
@ccclass
export default class ClickControl extends Component {
    @property(CCBoolean)
    bubbles:boolean=true
    @property(CCBoolean)
    stopEvent:boolean=false
    @property(Component)
    private excludes:Component[]=[]
    //start和end，两点之间允许的差距
    private dis=3
    //start和end之间允许的时间差(毫秒)
    private time=500
    //start点
    private startPoint:Vec2=v2(0,0)
    private startTime:number=0
    protected onLoad(): void {
        /*this.excludes.forEach((item)=>{
            console.log(item.node.uuid)
        })*/
    }
    protected onEnable(): void {
        //if(this.node.name=='SpriteSplash')console.log('ClickControl onEnable')
        this.node.on(NodeEventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(NodeEventType.TOUCH_END, this.onTouchEnd, this);
    }
    protected onDisable(): void {
        this.node.off(NodeEventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(NodeEventType.TOUCH_END, this.onTouchEnd, this);
    }
    private onTouchStart(e:EventTouch): void {
        //if(this.node.name=='SpriteSplash')console.log('ClickControl onTouchStart')
        //e.propagationImmediateStopped=this.stopEvent
        this.startPoint=e.getUILocation();
        this.startTime=Date.now()
    }
    private onTouchEnd(e:EventTouch): void {
        //console.log('ClickControl onTouchEnd')
        //e.propagationImmediateStopped=this.stopEvent
        
        //end点
        const endPoint=e.getUILocation();
        const distance=Math.sqrt(Math.pow(endPoint.x-this.startPoint.x,2)+Math.pow(endPoint.y-this.startPoint.y,2))
        //时间差
        const diffTime=Date.now()-this.startTime
        //判断是否触发click事件
        if(distance<this.dis&&diffTime<this.time){
            if(this.check(e.target)){
                return
            }
            const evt=new EventTouch(e.getTouches(),this.bubbles,'click',e.getTouches())
            evt.touch=e.touch
            this.node.dispatchEvent(evt)
        }
        //this.node.emit(NodeEventType.CLICK, e);
    }
    private check(target:Node):boolean{
        /*this.excludes.forEach((item)=>{
            if(item.node.uuid==target.uuid){
                return true
            }
        })*/
        for(let i=0;i<this.excludes.length;i++){
            if(this.excludes[i].node.uuid==target.uuid){
                return true
            }
        }
        return false
    }
}